package com.ytc.controller;

import com.ytc.dto.BookFeiLeiDto;

import com.ytc.mapper.CommentMapper;
import com.ytc.model.*;
import com.ytc.service.*;
import com.ytc.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 详细介绍类情况.
 *
 * @ClassName BookController
 * @Author zk
 * @Date 2023/1/9
 * @Version 1.0
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BooklistService booklistService;

    @Autowired
    private BookhistoryService bookhistoryService;

    @Autowired
    private BookshelfService bookshelfService;

    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 张阔：跳转举报页面
     * @param report
     * @param model
     * @return
     */
    @RequestMapping("reportBook")
    public String reportBook(Report report,Model model){
        model.addAttribute("r",report);
        return "common/reportBook";
    }

    /**
     * 张阔：新增举报
     * @param report
     */
    @RequestMapping("addReport")
    @ResponseBody
    public void addReport(Report report){
        reportService.addReport(report);
    }
    /**
     * 张阔：分类显示书籍
     * @param dto
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("queryBookByFeiLei")
    //@Cacheable(cacheNames = RedisKeyCommon.QUERY_BOOK_BY_DTO,key = "#dto.toString()+','+#page.cpage+','+#page.pageSize",condition = "#dto.key==null||#dto.key==''")
    public String queryBookByFeiLei(BookFeiLeiDto dto, PageUtil<Booklist> page, Model model){

        String key = dto.toString() + ",cpage=" +page.getCpage() + ",pageSize=" + page.getPageSize();
        ValueOperations<String, Object> sov = redisTemplate.opsForValue();

        //如何缓存有，则从缓存拿
        if (redisTemplate.hasKey(RedisKeyCommon.QUERY_BOOK_BY_DTO)){
            page = (PageUtil<Booklist>) sov.get(RedisKeyCommon.QUERY_BOOK_BY_DTO);
        }else {//没有则存入缓存
            //分页查询
            List<Booklist> list = booklistService.queryBookListByDto(dto);
            //查询每本书的总页数
            //查询更新日期
            for (Booklist b:list){
                b.setSumNum(booklistService.querySumNum(b.getBlId()));
                b.setNewDate( booklistService.queryNewDate(b.getBlId()));
                BookSortUtil.bookSort(b);
            }
            page = PageUtilHelper.pageHelper(list,page.getCpage(),page.getPageSize());
            sov.set(RedisKeyCommon.QUERY_BOOK_BY_DTO+"::"+key,page,15,TimeUnit.MINUTES);
        }
        model.addAttribute("pageInfo",page);
        if (dto!=null){
            if (dto.getShowtype()!=null){
                if(dto.getShowtype()==1){
                    return "book/showTuWenBookList";
                }else {
                    return "book/showWenZiBookList";
                }
            }else {
                return "book/showTuWenBookList";
            }
        }
        return "book/showTuWenBookList";
    }

    /**
     * 张阔：书籍阅读显示目录和信息
     * @param blId
     * @return
     */
    @RequestMapping("showBookInfo")
    public String showBookInfo(Integer blId,HttpServletRequest request,Model model){
        //查询该书籍
        Booklist book = booklistService.queryBookById(blId);
        //查询该书籍的总字数
        Long sumNum = booklistService.querySumNum(blId);
        book.setSumNum(sumNum);
        //查询书籍评分
        Double avgScore = booklistService.queryAvgScore(blId);
        book.setAvgScore(avgScore);
        //查询最新更新日期
        book.setNewDate(booklistService.queryNewDate(blId));
        model.addAttribute("b",book);
        //查询该书籍是否在书架中
        //获取用户登录
        User user = UserUtil.getUser(request);
        if (user!=null){
            Bookshelf bs = bookshelfService.queryShelfByUidAndBid(user.getUId(),blId);
            if (bs!=null){
                model.addAttribute("flag",true);
            }else {
                model.addAttribute("flag",false);
            }
        }else{
            model.addAttribute("flag",false);
        }
        //查询章节阅读权限
        model.addAttribute("readFlag",UserUtil.readFlag(user, userService));
        return "book/showBookInfo";
    }


    /**
     * 张阔：查询具体章节
     * @param bcid 章节id
     * @param blId 书籍id
     * @return
     */
    @RequestMapping("queryChapterById")
    public String queryChapterById(@RequestParam(value = "bcid",defaultValue = "-1") Integer bcid, @RequestParam(value = "blId",defaultValue = "-1") Integer blId, HttpServletRequest request, Model model){
        //点击阅读书籍，书籍点击量+1
        booklistService.updateBookCount(blId,bcid);
        //查询章节
        if(blId!=-1){
            //判读用户是否登录
            User user = UserUtil.getUser(request);
            if (user!=null){//登录后查询历史记录
                Integer bid = bookhistoryService.queryBhByUidAndBlid(user.getUId(),blId);
                if (bid!=null){
                    bcid = bid;
                    blId = -1;
                }
            }
        }
        Book chapter = booklistService.queryChapterById(bcid, blId);
        model.addAttribute("c",chapter);
        //查询书籍目录
        //查询该书籍
        Booklist book = booklistService.queryBookById(chapter.getBId());
        book.setNewDate(booklistService.queryNewDate(chapter.getBId()));
        //把book中的list排序
        BookSortUtil.bookSort(book);
        //查询章节阅读权限
        User user = UserUtil.getUser(request);
        boolean readFlag = UserUtil.readFlag(user, userService);
        model.addAttribute("readFlag",readFlag);

        //对权限不足的章节进行限制
        if(user==null && chapter.getBchapternum()>19){//未登录，跳转到登录页面
            return "redirect:/user/toLoginReader";//登录页面
        }else {
            if(!readFlag && chapter.getBchapternum()>19){//非会员，跳转到充值会员页面
                return "redirect:/user/toVip";
            }
        }
        //查询是否该用户已评论
        if(user!=null){
            //查询书评
            Comment comment = commentService.queryCommentByBidAndUid(book.getBlId(),user.getUId());
            if(comment!=null){
                model.addAttribute("commentFlag",false);
            }else {
                model.addAttribute("commentFlag",true);//是否显示书评
            }
        }else {
            model.addAttribute("commentFlag",false);
        }
        model.addAttribute("b",book);
        return "book/readBook";
    }

    /**
     * 张阔：新增历史记录
     * @param cid
     */
    @RequestMapping("addHistory")
    @ResponseBody
    public void addHistory(Integer bid,Integer cid,HttpServletRequest request){
        //获取用户
        User user = UserUtil.getUser(request);
        if (user!=null){
            //修改历史记录
            //查询历史记录，如果存在，修改，不存在新增
            Integer cId = bookhistoryService.queryBhByUidAndBlid(user.getUId(), bid);
            if(cId!=null){//存在，修改
                bookhistoryService.updateHistory(user.getUId(),bid,cid);
            }else {
                bookhistoryService.addHistory(user.getUId(),bid,cid);
            }
        }
    }

    /**
     * 张阔：新增书评
     * @param comment
     * @param request
     */
    @RequestMapping("addComment")
    @ResponseBody
    public void addComment(Comment comment,HttpServletRequest request){
        User user = UserUtil.getUser(request);
        if (user!=null){
            comment.setCUserid(user.getUId());
            commentService.addComment(comment);
        }
    }
}
